package com.knxhd.config;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.knxhd.entity.LlmMcpConfig;
import com.knxhd.service.LlmMcpConfigService;
import io.modelcontextprotocol.client.transport.HttpClientSseClientTransport;
import io.modelcontextprotocol.spec.McpClientTransport;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.mcp.client.autoconfigure.NamedClientMcpTransport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
@RequiredArgsConstructor
@Slf4j
public class McpConfig {

    private final LlmMcpConfigService llmMcpConfigService;


    @Bean
    public List<NamedClientMcpTransport> mcpClientTransport() {
        LambdaQueryWrapper<LlmMcpConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LlmMcpConfig::getStatus, 1);

        List<LlmMcpConfig> mcpConfigList = llmMcpConfigService.list(queryWrapper);

        List<NamedClientMcpTransport> mcpTransportList = new ArrayList<>();
        for (LlmMcpConfig llmMcpConfig : mcpConfigList) {
            if (StrUtil.isBlank(llmMcpConfig.getBaseUrl())) {
                continue;
            }
            log.info("MCP配置为:{}", JSONObject.toJSONString(llmMcpConfig));
            McpClientTransport transport = HttpClientSseClientTransport
                    .builder(llmMcpConfig.getBaseUrl())
                    .sseEndpoint(String.format("/sse?key=%s", llmMcpConfig.getApiKey()))
                    .objectMapper(new ObjectMapper())
                    .build();

            mcpTransportList.add(new NamedClientMcpTransport("amap", transport));
        }

        return mcpTransportList;
    }

}
